﻿function ECommerceRecommendationsViewModel(context) {

    var self = this;

    var spinner = new SpinnerModel();

    var productInfoRoute = context.spaRuntime.findRouteByName('product');

    var productsByTag = context.spaRuntime.findRouteByName('productsByTag');
    
    var products = ko.observableArray([]);

    function reload(ids) {
        var api = context.api();
        spinner.enter();
        api.recommendations.getByIds(ids, function (otherIds) {
            spinner.leave();

            var res = [];
            for (var i = 0; i < otherIds.length; i++) {
                var otherId = otherIds[i];
                spinner.enter();
                api.products.getById(otherId, function (data) {
                    spinner.leave();
                    res.push(new FullProductModel(data));
                    products(res);
                }, function () {
                    spinner.leave();
                });
            }
        }, function () {
            spinner.leave();
        });
    }

    function getProductUrl(product) {
        return productInfoRoute.formatHash({
            id: product.id()
        });
    }
    
    function getByTagUrl(tag) {
        return productsByTag.formatHash({
            tag: tag
        });
    }
    
    function addToCart(product) {
        context.addToCart(product);
        products.remove(product);
    }

    self.products = products;
    self.reload = reload;
    self.getProductUrl = getProductUrl;
    self.getByTagUrl = getByTagUrl;
    self.addToCart = addToCart;
}